package com.manyauthenticationway.server.manyauthenticationway.domain.user

import com.alibaba.fastjson.JSONObject
import com.example.securitydemoserver.exception.ExceptionDefine
import com.oauth.server.comoauth2server.domain.BaseService
import org.slf4j.LoggerFactory
import org.springframework.data.domain.Pageable
import org.springframework.data.mongodb.core.query.Criteria
import org.springframework.data.mongodb.core.query.Query
import org.springframework.security.core.userdetails.User
import org.springframework.security.core.userdetails.UserDetails
import org.springframework.security.core.userdetails.UserDetailsService
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder
import org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter
import org.springframework.stereotype.Service
import java.security.Principal

@Service("SysUserService")
class SysUserService: UserDetailsService, BaseService<SysUser>(SysUser::class.java) {
    private val logger = LoggerFactory.getLogger(SysUserService::class.java)
    override fun loadUserByUsername(username: String?): UserDetails {
        logger.info("username:"+username)
        val user=mongoTemplate.findOne(Query.query(Criteria.where("username").`is`(username)), SysUser::class.java);
        if(user==null) {
            ExceptionDefine().E10_0001//用户不存在
        }

        return User(user!!.username,user!!.password,user.authorities);
    }

    fun insert(sysUser: SysUser){
        mongoTemplate.insert(sysUser,"sysUser");
    }

    fun delete(sysUser: SysUser){
        mongoTemplate.remove(sysUser,"sysUser")
    }
    fun update(sysUser: SysUser): MutableMap<String, Any>{
        var result = mutableMapOf<String, Any>()
        val criteria= Criteria.where("id").`is`(sysUser.id)
        val user=mongoTemplate.findOne(Query.query(criteria),SysUser::class.java)
        mongoTemplate.update(SysUser::class.java)
        result.put("code","0000")
        result.put("data","")
        return result
    }
    fun queryByPage(params:Map<String,Any>, pageable: Pageable): MutableMap<String, Any> {
        var result= mutableMapOf<String, Any>()
        val criteria = Criteria()
        val page=findByPage(criteria, pageable)
        result.put("code","0000")
        result.put("data",page)
        return result
    }
    fun selectByOne(params: Map<String,Any>,principal: Principal): JSONObject {
        var result = JSONObject()
        val sysUser = mongoTemplate.findOne(Query.query(Criteria.where("id").`is`("157191d5-0528-46b9-b374-9c65721db8d1")), SysUser::class.java)?:ExceptionDefine().E10_0000
        result.put("data", sysUser)
        result.put("principal",principal)
        println()
        return result
    }
}
